import Touchable from '@/components/Touchable';
import React, {useEffect, useMemo} from 'react';
import {StyleSheet, Image, Animated, Easing} from 'react-native';
import Icon from '@/assets/iconfont/index';
import {RootState} from '@/models/index';
import {connect, ConnectedProps} from 'react-redux';
import Progress from './Progress';

const mapStateToProps = ({player}: RootState) => {
  return {
    thumbnailUrl: player.thumbnailUrl,
    playState: player.playState,
  };
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
  onPress: () => void;
}

const Play: React.FC<IProps> = props => {
  const {thumbnailUrl, playState} = props;

  const anim = useMemo(() => new Animated.Value(0), []);
  const rotate = useMemo(() => {
    return anim.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg'],
    });
  }, [anim]);
  const timing = useMemo(() => {
    return Animated.loop(
      Animated.timing(anim, {
        toValue: 1,
        duration: 10000,
        easing: Easing.linear,
        useNativeDriver: true,
      }),
      {iterations: -1}, //与loop开启无限动画
    );
  }, [anim]);

  useEffect(() => {
    console.log(1111);
    if (playState === 'playing') {
      timing.start();
    } else {
      timing.stop();
    }
  }, [playState, timing]);
  const onPress = () => {
    if (thumbnailUrl && props.onPress) {
      props.onPress();
    }
  };

  // useDidMount(() => {});

  return (
    <Touchable style={styles.play} onPress={onPress}>
      <Progress>
        <Animated.View style={{transform: [{rotate}]}}>
          {thumbnailUrl ? (
            <Image source={{uri: thumbnailUrl}} style={[styles.image]} />
          ) : (
            <Icon name="icon-bofang3" color="#ededed" size={40} />
          )}
        </Animated.View>
      </Progress>
    </Touchable>
  );
};

const styles = StyleSheet.create({
  play: {
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
    borderRadius: 21,
  },
  image: {
    width: 42,
    height: 42,
    borderRadius: 21,
  },
});

export default connector(Play);
